package com.cjm.concurrenttest;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 使用while解决只判断一次的问题 同时解决虚假唤醒的问题
 */
@Slf4j
public class TestWhileWait {
    static final Object room = new Object();
    static boolean hasCigarette = false; //默认没烟
    static boolean hasTakeout = false;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> {
            synchronized (room) {
                while(!hasCigarette) {
                    log.debug("没烟，休息");
                    try {
                        room.wait(); //用notify好过interrupted
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(hasCigarette) {
                    log.debug("有烟了 开始干活");
                }else {
                    log.debug("没得干活");
                }
            }
        },"xiao南").start();

        new Thread(() -> {
            synchronized (room) {
                while(!hasTakeout) {
                    log.debug("没外卖，休息");
                    try {
                        room.wait(); //用notify好过interrupted
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if(hasTakeout) {
                    log.debug("有外卖了 开始干活");
                } else {
                    log.debug("没得干活");
                }
            }
        },"xiao女").start();



        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            synchronized (room) {
                hasTakeout = true;
                log.debug("外卖到了");
                room.notify(); //随机唤醒 错误唤醒 使用notifyAll
            }

        },"送烟").start();
    }

}
